<template>
  <div class="edit-panel">
    <Anchor ref="insuranceAnchor" :labelList="insuranceLabels">
      <div id="row-01" class="box">
        <FormPanel
          ref="insuranceForm"
          :list="insuranceFormList"
          :cols="2"
          :labelWidth="110"
          @formChange="insuranceChangeHandle"
          :isSubmitBtn="false"
        ></FormPanel>
      </div>
      <div id="row-02" class="box">
        <FormPanel
          ref="ownerCarForm"
          :list="ownerCarFormList"
          :cols="3"
          :labelWidth="120"
          @formChange="ownerCarChangeHandle"
          :isSubmitBtn="false"
        ></FormPanel>
      </div>
      <div id="row-03" class="box">
        <FormPanel
          ref="insureInfoForm"
          :list="insureInfoFormList"
          :cols="3"
          :labelWidth="110"
          @formChange="insureInfoChangeHandle"
          :isSubmitBtn="false"
        ></FormPanel>
      </div>
      <div id="row-04">
        <FilterTable
          ref="insureDetailTable"
          :columns="insureDetailColumns"
          :isSelectColumn="false"
          height="280"
          :onColumnsChange="columns => this.insureDetailColumns = columns"
          :onSyncTableData="syncTableFun"
          :onCellChange="changeCells"
        >
          <!-- selectionType="single"
          :dataSource="insureDetailList"-->
          <template slot="controls">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-plus"
              @click="add()"
              v-show="type !='permission'"
            >新增</el-button>
          </template>
        </FilterTable>
      </div>
      <div id="row-05" class="box">
        <FormPanel
          ref="financeInfoForm"
          :list="financeInfoFormList"
          :cols="3"
          :labelWidth="110"
          @formChange="financeInfoChangeHandle"
          :isSubmitBtn="false"
        ></FormPanel>
      </div>
    </Anchor>
    <BaseDialog title="车主车辆信息查询" :visible.sync="lincenseSearchDialog" destroyOnClose>
      <LicenseSearch @saveDialog="getSelectLicense" @closeDialog="lincenseSearchDialog = false"></LicenseSearch>
    </BaseDialog>
    <BaseDialog title="险种选择" :visible.sync="InsureDialog" destroyOnClose>
      <Insure @saveDialog="getInsure" @closeDialog="InsureDialog = false"></Insure>
    </BaseDialog>
    <div class="confirm-button-style">
      <AjaxButton :click="saveDialog" type="primary" v-show="this.type !='permission'">保 存</AjaxButton>
      <AjaxButton :click="dele" type="primary" v-show="this.type =='modify'">删 除</AjaxButton>
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { retainValidNumbers } from '@/utils';
import LicenseSearch from './LicenseSea';
import Insure from './Insure';
import { detailedQuery, editQuery, addSave, editSave, insuranceCompany, deleteInsurance, vehicleOwnerInformation } from '@/api/derived/insurance/insurancePolicy';
import { constants } from 'buffer';
//查询保险顾问
import { searchRoleByCode } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import {phone,IDNumber} from '@/utils/validate'; //校验js引入

export default {
  name: 'Insuranceeditpanel',
  mixins: [dictionary],
  props: ['type', 'TBcode', 'rowData'],
  components: { LicenseSearch, Insure },
  data() {
    this.BaseTable = null;
    this.insuranceSaveData = null;
    this.ownerCarSaveData = null;
    this.insureInfoSaveData = null;
    this.financeInfoSaveData = null;
    this.dmsFunc = { dmsFuncId: 55100010 };

    return {
      insuranceLabels: [
        { title: '基本信息', id: 'row-01' },
        { title: '车主车辆信息', id: 'row-02' },
        { title: '投保信息', id: 'row-03' },
        { title: '保险列表', id: 'row-04' },
        { title: '金额信息', id: 'row-05' }
      ],

      insuranceFormList: this.createInsuranceFormList(),
      ownerCarFormList: this.createOwnerCarFormList(),
      insureInfoFormList: this.createInsureInfoFormList(),
      financeInfoFormList: this.createFinanceInfoFormList(),
      insureDetailList: [],
      insureDetailColumns: this.createInsureDetailColumns(),
      lincenseSearchDialog: false, // 车主编号
      InsureDialog: false, //table新增按钮
      lsita: [], //定义存放table
      items: [], //删除行
      listV: [],
      BRAND_ID: null,
      SERIES_ID: null,
      MODEL_ID: null,
      flagInsurance: '',
      flagOwnerCar: '',
      flagInsureInfo: '',
      flagfinanceInfo: '',
      allMoney: 0, //应收金额总（用于计算）
      forceInsurance: 0, //定义交强保险用于判断
      businessInsurance: 0 //定义商业保险

      //  refresh:refresh,//定义刷新
    };
  },
  methods: {
    createInsuranceFormList() {
      return [
        {
          type: 'INPUT',
          label: '投保单号',
          fieldName: 'PROPOSAL_CODE',
          disabled: true,
          placeholder: '投保单号...'
        },
        {
          type: 'SELECT',
          label: '投保类型',
          fieldName: 'PROPOSAL_TYPE',
          itemList: this.createDictList('8086'),
          change: val => {
            this.changeRenewInsurance(val);
          },
          rules: [{ required: true, message: '请选择投保类型', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '是否新增续保',
          fieldName: 'IS_ADD_PROPOSAL',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否本公司投保',
          fieldName: 'IS_SELF_COMPANY_INSURANCE',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        }
      ];
    },
    createOwnerCarFormList() {
      return [
        {
          type: 'INPUT',
          label: '车主编号',
          fieldName: 'ORG_CUS_NO',
          readonly: true,
          initialValue: null,
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.openOrderNoHandle}></el-button>;
          },
          onEnter: val => {
            this.lincenseSearchDialog = val;
            this.openOrderNoHandle();
          }
        },
        {
          type: 'INPUT',
          label: '车主名称',
          fieldName: 'OWNER_NAME',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '电话',
          fieldName: 'OWNER_PHONE',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'OWNER_PROPERTY',
          disabled: true,
          itemList: this.createDictList('8011')
        },
        {
          type: 'INPUT',
          label: '手机',
          fieldName: 'OWNER_MOBILE',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '邮编',
          fieldName: 'OWNER_ZIP_CODE',
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '地址',
          fieldName: 'OWNER_ADDRESS',
          rows: 1,
          maxlength: 120,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'LICENSE',
          disabled: true
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'VIN',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '发动机号',
          fieldName: 'ENGINE_NO',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '核定载客',
          fieldName: 'APPROVED_CUSTOMER_COUNT'
        },
        {
          type: 'INPUT',
          label: '核定载客质量(kg)',
          fieldName: 'APPROVED_CUSTOMER_QUALITY'
        },
        {
          type: 'INPUT',
          label: '排量/功率(L/K)',
          fieldName: 'ENGINE_DESC',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '已使用年限',
          fieldName: 'USED_YEAR'
        },
        {
          type: 'DATE',
          label: '初次登记日期',
          fieldName: 'FIRST_REGISTER_DATE',
          dateType: 'exactdate'
        },
        {
          type: 'SELECT',
          label: '机动车种类',
          fieldName: 'VEHICLE_TYPE',
          change: val => {},
          itemList: this.createDictList('8073')
        },
        {
          type: 'SELECT',
          label: '机动车使用性质',
          fieldName: 'VEHICLE_USE_NATURE',
          itemList: this.createDictList('8061'),
          rules: [{ required: true, message: '这是必填字段', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'BRAND_NAME',
          disabled: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'SERIES_NAME',
          disabled: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'MODEL_NAME',
          disabled: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '颜色',
          fieldName: 'COLOR_NAME',
          disabled: true,
          itemList: []
        },
        // {
        //   type: 'SELECT',
        //   label: '销售模式',
        //   fieldName: 'SALES_MODEL',
        //   itemList: []
        // },
        {
          type: 'DATE',
          label: '车辆销售日期',
          fieldName: 'SALES_DATE',
          dateType: 'exactdate'
        },
        {
          type: 'SELECT',
          label: '保险顾问',
          fieldName: 'INS_BROKER',
          itemList: [],
          rules: [{ required: true, message: '这是必填字段', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'SO_NO',
          disabled: true
        }
        // {
        //   type: 'INPUT',
        //   label: '车辆购置税',
        //   fieldName: 'TAX_SUM'
        // }
      ];
    },
    createInsureInfoFormList() {
      return [
        {
          type: 'INPUT',
          label: '投保人姓名',
          fieldName: 'PROPOSAL_NAME'
        },
        {
          type: 'INPUT',
          label: '电话',
          fieldName: 'PHONE',
          rules: [{ trigger: 'blur'}]
        },
        {
          type: 'INPUT',
          label: '手机',
          fieldName: 'MOBILE',
          // maxlength: 11,
          rules: [{ required: true, trigger: 'blur', message: '请输入手机号' },{ trigger: 'blur',  validator:phone }]
        },
        {
          type: 'INPUT',
          label: '邮编',
          fieldName: 'ZIP_CODE'
        },
        {
          type: 'TEXT_AREA',
          label: '地址',
          fieldName: 'ADDRESS',
          rows: 1,
          maxlength: 120
        },
        {
          type: 'INPUT',
          label: '被保险人',
          fieldName: 'INSURED_NAME',
          rules: [{ required: true, message: '这是必填字段', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '证件类别',
          fieldName: 'CT_CODE',
          itemList: this.createDictList('8013'),
          change: val => {
            this.changeCarType(val);
          },
          rules: [{ required: true, message: '这是必填字段', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '证件号码',
          fieldName: 'CERTIFICATE_NO',
          maxlength: 18,
          rules: [{ required: true, trigger: 'blur', message: '请输入证件号码' }]
        },
        // {
        //   type: 'SELECT',
        //   label: '与机动车关系',
        //   fieldName: 'VEHICLE_RELATION',
        //   itemList: []
        // },
        {
          type: 'SELECT',
          label: '是否本地投保',
          fieldName: 'IS_INS_LOCAL',
          placeholder: '请选择',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '这是必填字段', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '是否信贷投保',
          fieldName: 'IS_INS_CREDIT',
          placeholder: '请选择',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '这是必填字段', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '保险公司',
          fieldName: 'INSURATION_CODE',
          initialValue: null,
          itemList: [],
          rules: [{ required: true, message: '这是必填字段', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '投保渠道',
          fieldName: 'INS_CHANNELS',
          itemList: this.createDictList('8062'),
          rules: [{ required: true, message: '这是必填字段', trigger: 'change' }]
        },
        {
          type: 'DATE',
          label: '保险销售日期',
          fieldName: 'INS_SALES_DATE',
          dateType: 'exactdate'
        },
        {
          type: 'INPUT',
          label: '交强险保单号',
          fieldName: 'COM_INS_CODE'
        },
        {
          type: 'INPUT',
          label: '商业险保单号',
          fieldName: 'BUSI_INS_CODE'
        }
      ];
    },
    createFinanceInfoFormList() {
      return [
        {
          type: 'INPUT_NUMBER',
          label: '交强险应收金额',
          fieldName: 'RECEIVABLE_COM_AMOUNT',
          disabled: true,
          precision: 2,
          initialValue: 0.0,
          min: 0.0
        },
        {
          type: 'INPUT_NUMBER',
          label: '商业险应收金额',
          fieldName: 'RECEIVABLE_BUSI_AMOUNT',
          disabled: true,
          precision: 2,
          initialValue: 0.0,
          min: 0.0
        },
        {
          type: 'INPUT_NUMBER',
          label: '优惠金额',
          fieldName: 'TOTAL_DISCOUNT_AMOUNT',
          disabled: true,
          precision: 2,
          initialValue: 0.0,
          min: 0.0,
          change: val => {
            this.changeDiscountInsurance(val);
          }
        },
        {
          type: 'SELECT',
          label: '是否代收',
          fieldName: 'IS_COLLECTION',
          change: val => {},
          itemList: this.createDictList('1004')
        },
        {
          type: 'INPUT_NUMBER',
          label: '交强险返利金额',
          fieldName: 'COM_INSURANCE_REBATE_AMT',
          disabled: true,
          precision: 2,
          initialValue: 0.0,
          min: 0.0
        },
        {
          type: 'INPUT_NUMBER',
          label: '商业险返利金额',
          fieldName: 'BUSI_INSURANCE_REBATE_AMT',
          disabled: true,
          precision: 2,
          initialValue: 0.0,
          min: 0.0
        },
        {
          type: 'INPUT_NUMBER',
          label: '车船税',
          fieldName: 'TRAVEL_TAX_AMOUNT',
          disabled: true,
          precision: 2,
          initialValue: 0.0,
          min: 0.0,
          change: val => {
            this.changeTax(val);
          }
        },
        {
          type: 'SELECT',
          label: '是否返利付讫',
          fieldName: 'IS_PAYOFF_REBATE',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'INPUT_NUMBER',
          label: '其他业务',
          fieldName: 'OTHER_AMOUNT',
          disabled: true,
          precision: 2,
          initialValue: 0.0,
          min: 0.0,
          change: val => {
            this.changeOther(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '总金额(应收)',
          fieldName: 'RECEIVEABLE_TOTAL_AMOUNT',
          disabled: true,
          precision: 2,
          initialValue: 0.0,
          min: 0.0
        },
        {
          type: 'INPUT_NUMBER',
          label: '总金额(实际)',
          fieldName: 'TOTAL_AMOUNT',
          disabled: true,
          precision: 2,
          initialValue: 0.0,
          min: 0.0
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'REMARK'
        }
      ];
    },
    createInsureDetailColumns() {
      return [
        {
          title: '操作',
          width: 100,
          fixed: 'left',
          hidden: false,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.delFun(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '险种名称',
          dataIndex: 'INSURANCE_TYPE_NAME',
          sorter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '险种类型',
          dataIndex: 'INSURANCE_TYPE_LEVEL',
          sorter: true,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.INSURANCE_TYPE_LEVEL, '1047')}</span>;
          }
        },
        {
          title: '保额',
          dataIndex: 'PROPOSAL_AMOUNT',
          sorter: true,
          filter: true,
          editable: true,
          disabled: this.show(this.type),
          editType: 'number',
          precision: 2,
          rules: [{ required: true, message: '请填写备注', trigger: 'blur' }]
        },
        {
          title: '应收金额',
          dataIndex: 'RECEIVABLE_AMOUNT',
          sorter: true,
          filter: true,
          disabled: this.show(this.type),
          editable: true,
          editType: 'number',
          precision: 2,
          rules: [{ required: true, message: '请填写备注', trigger: 'blur' }]
        },
        {
          title: '开始日期',
          dataIndex: 'BEGIN_DATE',
          width: 150,
          sorter: true,
          editable: true,
          disabled: this.show(this.type),
          editType: 'date-picker',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '结束日期',
          dataIndex: 'END_DATE',
          width: 150,
          sorter: true,
          editable: true,
          disabled: this.show(this.type),
          editType: 'date-picker',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '是否赠送',
          dataIndex: 'IS_PRESENTED',
          sorter: true,
          editable: true,
          disabled: this.show(this.type),
          editType: 'checkbox',
          editItems: [{ text: '', trueValue: '10041001' }, { text: '', falseValue: '10041002' }]
        },
        {
          title: '是否交强险',
          dataIndex: 'IS_COM_INSURANCE',
          sorter: true,
          hidden: true
        },
        {
          title: '明细主键',
          dataIndex: 'ITEM_ID',
          sorter: true,
          hidden: true
        }
      ];
    },
    //改变证件类型,证件类型为身份证的时候加校验
    changeCarType(val){
      console.log(val,"val11")
      if(val==80131001){
        this.insureInfoFormList.find(item => item.fieldName === 'CERTIFICATE_NO').rules= [{ required: true, trigger: 'blur', message: '请输入证件号码' },{ trigger: 'blur',  validator:IDNumber}]
      }else{
       this.insureInfoFormList.find(item => item.fieldName === 'CERTIFICATE_NO').rules= [{ required: true, trigger: 'blur', message: '请输入证件号码' }]
      
      }
    
    },
    //修改投保单类型,对新增续保进行赋值操作
    changeRenewInsurance() {
      this.insuranceFormList.find(item => item.fieldName === 'IS_ADD_PROPOSAL').initialValue = 10041002;
    },
    //table中数据发生变化时候改变时间
    changeCells(keys, obj) {
      debugger;
      let list = this.BaseTable.dataSource;
      console.log(keys, obj, '数据');
      let key = Object.keys(keys)[0];
      let a = key.substring(key.indexOf('|') + 1);
      console.log(obj.BEGIN_DATE, 'BEGIN_DATE');

      if (a == 'BEGIN_DATE') {
        console.log('BEGIN_DATE');
        var date = new Date(obj.BEGIN_DATE);
        let time5 = date.setDate(date.getDate() - 1); //前一天
        var d = new Date(time5); //定义时间
        let year = d.getFullYear() + 1; //获取年
        let min = d.getMonth() + 1; //获取月
        let time = d.getDate(); //获取天数
        let aa = year + '-' + min + '-' + time; //拼接获取年月日

        list.forEach(x => {
          x.BEGIN_DATE = obj.BEGIN_DATE;
          x.END_DATE = aa;
        });
      }
      if (a == 'END_DATE') {
        list.forEach(x => {
          x.END_DATE = obj.END_DATE;
        });
      }
    },

    //同步table数据的方法
    syncTableFun(val) {
      this.lsita = val;
      console.log(this.lsita, 'lsita');

      let strongInsuranceAmount = 0; //交强险总金额
      let businessInsuranceAmount = 0; //商业保险总金额
      let totalAmount = 0; //总金额应收
      let totalCostAmount = 0; //总金额实际
      let beginDate = ''; //定义开始日期
      let endDate = ''; //定义结束日期
      let discountAmount = 0; //优惠金额
      let vesselsTax = 0; //车船税
      let otherAmount = 0; //其他金额

      val.forEach(x => {
        // 如果是赠送的保险则不计划金额在内
        if (x.IS_PRESENTED == 10041002) {
          //判断险种类型如果是交强
          if (x.INSURANCE_TYPE_LEVEL == 10471001) {
            strongInsuranceAmount += Number(x.RECEIVABLE_AMOUNT);
          } else if (x.INSURANCE_TYPE_LEVEL == 10471002) {
            businessInsuranceAmount += Number(x.RECEIVABLE_AMOUNT);
          }
        }
      });
      //优惠金额
      const discountMoney = this.financeInfoFormList.find(item => item.fieldName === 'TOTAL_DISCOUNT_AMOUNT').initialValue;
      //车船税
      const taxMoney = this.financeInfoFormList.find(item => item.fieldName === 'TRAVEL_TAX_AMOUNT').initialValue;
      //其他费用
      const otherMoney = this.financeInfoFormList.find(item => item.fieldName === 'OTHER_AMOUNT').initialValue;
      //优惠金额赋值操作
      if (discountMoney != null) {
        discountAmount = discountMoney;
      }
      //车船税赋值操作
      if (taxMoney != null) {
        vesselsTax = taxMoney;
      }
      //其他费用赋值操作
      if (otherMoney != null) {
        otherAmount = otherMoney;
      }
      //应收总金额=交强险总金额+商业险总金额+其他金额+车船税
      totalAmount = strongInsuranceAmount + businessInsuranceAmount + vesselsTax + otherAmount;
      //实际总金额=应收总金额-优惠金额
      totalCostAmount = totalAmount - discountAmount;
      //把相关金额的值,进行赋值操作
      this.financeInfoFormList.find(item => item.fieldName === 'RECEIVABLE_COM_AMOUNT').initialValue = retainValidNumbers(strongInsuranceAmount);
      this.financeInfoFormList.find(item => item.fieldName === 'RECEIVABLE_BUSI_AMOUNT').initialValue = retainValidNumbers(businessInsuranceAmount);
      this.financeInfoFormList.find(item => item.fieldName === 'RECEIVEABLE_TOTAL_AMOUNT').initialValue = retainValidNumbers(totalAmount);
      this.financeInfoFormList.find(item => item.fieldName === 'TOTAL_AMOUNT').initialValue = retainValidNumbers(totalCostAmount);
      //应收总金额赋值
      this.allMoney = retainValidNumbers(totalAmount);
    },
    //根据优惠金额修改总金额
    changeDiscountInsurance(val) {
      debugger;
      const tax = this.financeInfoFormList.find(item => item.fieldName === 'TRAVEL_TAX_AMOUNT').initialValue;
      const other = this.financeInfoFormList.find(item => item.fieldName === 'OTHER_AMOUNT').initialValue;
      this.financeInfoFormList.find(item => item.fieldName === 'TOTAL_AMOUNT').initialValue = retainValidNumbers(Number(this.allMoney) + Number(other) + Number(tax) - Number(val));
    },
    //根据车船税修改总金额
    changeTax(val) {
      const discount = this.financeInfoFormList.find(item => item.fieldName === 'TOTAL_DISCOUNT_AMOUNT').initialValue;
      const other = this.financeInfoFormList.find(item => item.fieldName === 'OTHER_AMOUNT').initialValue;
      this.financeInfoFormList.find(item => item.fieldName === 'TOTAL_AMOUNT').initialValue = retainValidNumbers(Number(this.allMoney) + Number(val) + Number(other) - Number(discount));
      this.financeInfoFormList.find(item => item.fieldName === 'RECEIVEABLE_TOTAL_AMOUNT').initialValue = retainValidNumbers(Number(this.allMoney) + Number(val) + Number(other));
    },
    //根据其他业务
    changeOther(val) {
      const discount = this.financeInfoFormList.find(item => item.fieldName === 'TOTAL_DISCOUNT_AMOUNT').initialValue;
      const tax = this.financeInfoFormList.find(item => item.fieldName === 'TRAVEL_TAX_AMOUNT').initialValue;
      this.financeInfoFormList.find(item => item.fieldName === 'TOTAL_AMOUNT').initialValue = retainValidNumbers(Number(this.allMoney) + Number(val) + Number(tax) - Number(discount));
      this.financeInfoFormList.find(item => item.fieldName === 'RECEIVEABLE_TOTAL_AMOUNT').initialValue = retainValidNumbers(Number(this.allMoney) + Number(val) + Number(tax));
    },
    //保险公司
    async insuranceCompany() {
      const res = await insuranceCompany();
      console.log('保险公司', res);
      this.insureInfoFormList.find(item => item.fieldName === 'INSURATION_CODE').itemList = res.data.map(x => ({ value: x.INSURATION_CODE, text: x.INSURATION_NAME }));
    },
    // 保险顾问
    async queryInsService() {
      let roleParam = { role: dictCode.INSURANCE_SPECIALIST };
      const res = await searchRoleByCode(roleParam);
      console.log('保险顾问', res);
      this.ownerCarFormList.find(item => item.fieldName === 'INS_BROKER').itemList = res.data.map(x => ({ value: x.userId + '', text: x.employeeName }));
    },
    //根据type类别显示列是否能编辑
    show(val) {
      if (val == 'permission') {
        return true;
      } else {
        return false;
      }
    },

    //明细带过来 请求
    async initSearch() {
      let res = await detailedQuery(this.TBcode);
      if (res.data.length > 0) {
        this.insureDetailList = res.data;
        this.BaseTable.EXECUTE_INSERT(this.insureDetailList);
      }
    },
    async editQuery() {
      let res = await editQuery(this.TBcode);
      let obj = res.data[0];
      this.BRAND_ID = obj.BRAND_ID;
      this.SERIES_ID = obj.SERIES_ID;
      this.MODEL_ID = obj.MODEL_ID;
      if (res.resultCode == 200) {
        let arimsArr = [];
        for (let [key, val] of Object.entries(obj)) {
          let param = {
            fieldName: key,
            value: val
          };
          let arr = ['INS_SALES_DATE', 'FIRST_REGISTER_DATE', 'SALES_DATE'];
          arr.some(item => {
            if (param.fieldName === item) {
              param.value = moment(param.val).format('YYYY-MM-DD HH:mm:ss');
              return true;
            }
          });

          arimsArr.push(param);
        }
        this.syncFormListData(arimsArr);
      }
    },

    syncFormListData(dataList) {
      // dataList 格式 -> [{ fieldName: 'xxx', value: 'xxx' }, ...]
      const formList = [...this.insuranceFormList, ...this.ownerCarFormList, ...this.insureInfoFormList, ...this.financeInfoFormList];
      const formFieldNames = formList.map(x => x.fieldName);

      dataList.forEach(x => {
        if (formFieldNames.includes(x.fieldName)) {
          let target = formList.find(k => k.fieldName === x.fieldName);
          if (!target) return;
          target.initialValue = x.value;
        }
      });
    },
    //带条件查询车主车辆信息
    async ownerQuery() {
      console.log(this.rowData, '收到的值');

      let res = await vehicleOwnerInformation(this.rowData.ORG_CUS_NO, this.rowData.VIN);

      if (res.resultCode == 200) {
        let obj = res.data[0];
        let listDa = [];

        console.log(res.data, '车主');

        for (let [key, val] of Object.entries(obj)) {
          let param = {
            fieldName: key,
            value: val
          };
          listDa.push(param);
        }

        const formList = [...this.ownerCarFormList];
        const formFieldNames = formList.map(x => x.fieldName);

        listDa.forEach(x => {
          if (formFieldNames.includes(x.fieldName)) {
            let target = formList.find(k => k.fieldName === x.fieldName);
            if (!target) return;
            target.initialValue = x.value;
          }
        });
      }
    },
    insuranceChangeHandle(val) {
      this.flagInsurance = true;
      this.insuranceSaveData = val;
    },
    ownerCarChangeHandle(val) {
      this.flagOwnerCar = true;
      this.ownerCarSaveData = val;
    },
    insureInfoChangeHandle(val) {
      this.flagInsureInfo = true;
      this.insureInfoSaveData = val;
    },
    financeInfoChangeHandle(val) {
      this.flagfinanceInfo = true;
      this.financeInfoSaveData = val;
    },
    async saveDialog() {
      //车主信息不能为空
      //交强险
      const  aa =this.insureInfoFormList.find(item => item.fieldName === 'COM_INS_CODE').initialValue;
      //商业险
      const  bb =this.insureInfoFormList.find(item => item.fieldName === 'BUSI_INS_CODE').initialValue;

      console.log(aa,"aa",bb,"bb")
      if (this.ownerCarFormList[0].initialValue == null) {
        return this.$notify.warning({ title: '提示信息', message: '请选择车主信息！' });
      }

      if (!this.insureDetailList.length) {
        return this.$notify.warning({ title: '提示信息', message: '投保明细信息不能为空' });
      }

      console.log(this.lsita, '结果集');
      for (let i = 0; i < this.lsita.length; i++) {
        if (this.lsita[i].PROPOSAL_AMOUNT == '') {
          return this.$notify.warning({ title: '提示信息', message: '保额不能为空' });
        }
      }
      for (let i = 0; i < this.lsita.length; i++) {
        if (this.lsita[i].BEGIN_DATE == '') {
          return this.$notify.warning({ title: '提示信息', message: '开始日期不能为空' });
        }
      }

      for (let i = 0; i < this.lsita.length; i++) {
        if (this.lsita[i].END_DATE == '') {
          return this.$notify.warning({ title: '提示信息', message: '结束日期不能为空' });
        }
      }

      for (let i = 0; i < this.lsita.length; i++) {
        //交强险赋值
        if (this.lsita[i].INSURANCE_TYPE_LEVEL == 10471001) {
          this.forceInsurance = 10471001;
          //商业险赋值
        } else if (this.lsita[i].INSURANCE_TYPE_LEVEL == 10471002) {
          this.businessInsurance = 10471002;
        }
      }
      //对交强险保单号,商业险保单号校验
      if (this.forceInsurance != 0) {
        if(aa ==null || aa===undefined ||aa=='' )
        return this.$notify.warning({ title: '提示信息', message: '有交强险明细,请填写交强险保险号' });
      }
      if (this.businessInsurance != 0) {
        if(bb==null || bb===undefined || bb=='')
        return this.$notify.warning({ title: '提示信息', message: '有商业险明细,请填写商业险保险号' });
      }

      this.flagInsurance = false;
      this.flagOwnerCar = false;
      this.flagInsureInfo = false;
      this.flagfinanceInfo = false;
      this.$set(this.listV, 'BRAND_ID', this.BRAND_ID);
      this.$set(this.listV, 'SERIES_ID', this.SERIES_ID);
      this.$set(this.listV, 'MODEL_ID', this.MODEL_ID);
      console.log(this.listV, '品牌等ID的值');
      this.$refs.insuranceForm.SUBMIT_FORM();
      this.$refs.ownerCarForm.SUBMIT_FORM();
      this.$refs.insureInfoForm.SUBMIT_FORM();
      this.$refs.financeInfoForm.SUBMIT_FORM();
      this.BaseTable.GET_REQUIRED_ERROR();
      let inss = [];
      if (this.flagInsurance == true && this.flagOwnerCar == true && this.flagInsureInfo == true && this.flagfinanceInfo == true) {
        if (this.type == 'add') {
          inss = await addSave({
            ...this.insuranceSaveData,
            ...this.ownerCarSaveData,
            ...this.insureInfoSaveData,
            ...this.financeInfoSaveData,
            ...this.listV,
            dms_insure: this.lsita,
            items: this.items.join()
          });
        } else if (this.type == 'modify') {
          console.log(this.items);
          //是否有删除行
          if (this.items.length > 0) {
            inss = await editSave({
              ...this.insuranceSaveData,
              ...this.ownerCarSaveData,
              ...this.insureInfoSaveData,
              ...this.financeInfoSaveData,
              ...this.listV,
              dms_insure: this.lsita,
              items: this.items.join()
            });
          } else {
            inss = await editSave({ ...this.insuranceSaveData, ...this.ownerCarSaveData, ...this.insureInfoSaveData, ...this.financeInfoSaveData, ...this.listV, dms_insure: this.lsita, items: null });
          }
        }
        if (inss.resultCode == 200) {
          this.listV = [];
          this.$notify.success({ title: '提示信息', message: '保存成功' });
          let List = {
            stutas: false,
            result: 'refresh'
          };
          console.log(List, '返回父类的集合');
          this.$emit('saveDialog', List);
        } else {
          return this.$notify.error({ title: '提示信息', message: inss.errMsg });
        }
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请填写必填项相关信息再进行操作' });
      }
    },
    closeDialog() {
      this.$emit('close', false);
    },
    openOrderNoHandle() {
      this.lincenseSearchDialog = true;
    },
    add() {
       const  insuranceCompany =this.insureInfoFormList.find(item => item.fieldName === 'INSURATION_CODE').initialValue;
      if (insuranceCompany == null) {
        return this.$notify.warning({ title: '操作结果', message: '请选择保险公司' });
      }
      this.InsureDialog = true;
    },
    getSelectLicense(arr) {
      //车主编号
      console.log(arr[0], '车主的值');
      this.BRAND_ID = arr[0].BRAND;
      this.SERIES_ID = arr[0].SERIES;
      this.MODEL_ID = arr[0].MODEL;
      console.log(this.BRAND_ID, this.SERIES_ID, this.MODEL_ID, '品牌,车系,车型的值');
      if (arr[0].OWNER_NO != null) {
        this.ownerCarFormList[0].initialValue = arr[0].OWNER_NO;
      }
      //车主名称,投保人,被保险人
      if (arr[0].OWNER_NAME != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'OWNER_NAME').initialValue = arr[0].OWNER_NAME;
        this.insureInfoFormList.find(item => item.fieldName === 'PROPOSAL_NAME').initialValue = arr[0].OWNER_NAME;
        this.insureInfoFormList.find(item => item.fieldName === 'INSURED_NAME').initialValue = arr[0].OWNER_NAME;
      }
      //电话
      if (arr[0].PHONE != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'OWNER_PHONE').initialValue = arr[0].PHONE;
        this.insureInfoFormList.find(item => item.fieldName === 'PHONE').initialValue = arr[0].PHONE;
      }
      //客户类型
      if (arr[0].OWNER_PROPERTY != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'OWNER_PROPERTY').initialValue = arr[0].OWNER_PROPERTY;
      }
      //手机
      if (arr[0].MOBILE != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'OWNER_MOBILE').initialValue = arr[0].MOBILE;
        this.insureInfoFormList.find(item => item.fieldName === 'MOBILE').initialValue = arr[0].MOBILE;
      }
      //邮编
      if (arr[0].ZIP_CODE != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'OWNER_ZIP_CODE').initialValue = arr[0].ZIP_CODE;
        this.insureInfoFormList.find(item => item.fieldName === 'ZIP_CODE').initialValue = arr[0].ZIP_CODE;
      }
      //地址
      if (arr[0].ADDRESS != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'OWNER_ADDRESS').initialValue = arr[0].ADDRESS;
        this.insureInfoFormList.find(item => item.fieldName === 'ADDRESS').initialValue = arr[0].ADDRESS;
      }
      //车牌号
      if (arr[0].LICENSE != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'LICENSE').initialValue = arr[0].LICENSE;
      }
      //VIN
      if (arr[0].VIN != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'VIN').initialValue = arr[0].VIN;
      }
      //发动机号
      if (arr[0].ENGINE_NO != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'ENGINE_NO').initialValue = arr[0].ENGINE_NO;
      }
      //排量/功率(L/K)
      if (arr[0].ENGINE_DESC != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'ENGINE_DESC').initialValue = arr[0].ENGINE_DESC;
      }
      //品牌
      if (arr[0].BRAND_NAME != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'BRAND_NAME').initialValue = arr[0].BRAND_NAME;
      }
      //车系
      if (arr[0].SERIES_NAME != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'SERIES_NAME').initialValue = arr[0].SERIES_NAME;
      }
      // 车型
      if (arr[0].MODEL_NAME != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'MODEL_NAME').initialValue = arr[0].MODEL_NAME;
      }
      //颜色
    if (arr[0].COLOR_NAME != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'COLOR_NAME').initialValue = arr[0].COLOR_NAME;
      }

      // 销售日期
      if (arr[0].SALES_DATE != null) {
        this.ownerCarFormList.find(item => item.fieldName === 'SALES_DATE').initialValue = arr[0].SALES_DATE;
      }

      //证件类别
      if (arr[0].CERTIFICATE_TYPE != null) {
      const card  = this.insureInfoFormList.find(item => item.fieldName === 'CT_CODE').initialValue = arr[0].CERTIFICATE_TYPE;
      //当赋值证件类别的时候,对身份号的校验规则进行改变
      this.changeCarType(card);

      }
      //证件号码
      if (arr[0].CERTIFICATE_CODE != null) {
        this.insureInfoFormList.find(item => item.fieldName === 'CERTIFICATE_NO').initialValue = arr[0].CERTIFICATE_CODE;
      }

      this.lincenseSearchDialog = false;
    },
    getInsure(arr) {
      console.log(arr, 'arr');
      console.log(this.lsita,"val")
//对险种判断是否有重复
        if (this.lsita.length > 0) {
          for(let i=0;i<this.lsita.length;i++){
            for(let j=0;j<arr.length;j++){
               if(this.lsita[i].INSURANCE_TYPE_NAME==arr[j].INSURANCE_TYPE_NAME){
                 return this.$notify.warning({ title: '提示信息', message: this.lsita[i].INSURANCE_TYPE_NAME+'重复，不允许重复添加!' });
               }
            } 
          }
        }



      this.InsureDialog = false;
      this.insureDetailList = arr;
      this.BaseTable.EXECUTE_INSERT(arr);
    },
    //删除
    async dele() {
      let res = await deleteInsurance(this.TBcode);
      if (res.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '删除成功' });
        let List = {
          stutas: false,
          result: 'refresh'
        };
        console.log(List, '删除');
        this.$emit('saveDialog', List);
      } else {
        return this.$notify.error({ title: '提示信息', message: res.errMsg });
      }
    },
    // 表格内 删除操作
    delFun(row) {
      this.items.push(row.ITEM_ID);
      console.log(this.items, '删除行');
      this.BaseTable.EXECUTE_DELETE([row]);
    }
  },

  mounted() {
    this.BaseTable = this.$refs.insureDetailTable.$refs.pageTable;
    this.insuranceCompany();
    this.queryInsService();
    setTimeout(() => {
      this.$refs.insuranceAnchor.REFRESH();
    }, 100);
  },
  created() {
    //获取明细查询
    if (this.type == 'permission') {
      this.insureDetailColumns[0].hidden = true;
      this.initSearch();
      this.editQuery();
      this.ownerQuery();
      this.insuranceFormList.forEach(x => {
        x.disabled = true;
      });
      this.ownerCarFormList.forEach(x => {
        x.disabled = true;
      });
      this.insureInfoFormList.forEach(x => {
        x.disabled = true;
      });
      this.financeInfoFormList.forEach(x => {
        x.disabled = true;
      });
    }
    if (this.type == 'modify') {
      this.initSearch();
      this.editQuery();
      this.ownerQuery();
    }
    if (this.type == 'add') {
      this.financeInfoFormList.find(item => item.fieldName === 'TOTAL_DISCOUNT_AMOUNT').disabled = false;
      this.financeInfoFormList.find(item => item.fieldName === 'COM_INSURANCE_REBATE_AMT').disabled = false;
      this.financeInfoFormList.find(item => item.fieldName === 'BUSI_INSURANCE_REBATE_AMT').disabled = false;
      this.financeInfoFormList.find(item => item.fieldName === 'TRAVEL_TAX_AMOUNT').disabled = false;
      this.financeInfoFormList.find(item => item.fieldName === 'OTHER_AMOUNT').disabled = false;
    }
  }
};
</script>

<style lang="less" scoped>
.edit-panel {
  height: calc(100vh - 135px);
  .min-height {
    height: 100%;
  }
}
.box {
  border: 1px solid #ccc;
  padding-top: 15px;
  padding-right: 15px;
  border-radius: @borderRadius;
  margin-bottom: 20px;
  box-shadow: @boxShadow;
}
.confirm-button-style {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 9;
  border-top: 1px solid #e9e9e9;
  padding: 10px 20px;
  background: #fff;
  text-align: right;
}
</style>

